package com.heiko.myopenglrecord2

import android.graphics.SurfaceTexture
import android.graphics.SurfaceTexture.OnFrameAvailableListener
import android.opengl.GLSurfaceView
import android.util.Log
import androidx.camera.core.Preview
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

class CameraRender(private val cameraView: CameraView) : GLSurfaceView.Renderer,
    Preview.OnPreviewOutputUpdateListener, OnFrameAvailableListener {
    private val TAG = "CameraRender"
    private lateinit var myFilter: MyFilter
    private var textures = intArrayOf(1)
    private lateinit var cameraTexture: SurfaceTexture
    private var matrix = FloatArray(16)

    //步骤二
    override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
        Log.i(TAG,"onSurfaceCreated")
        cameraTexture.attachToGLContext(textures[0])
        cameraTexture.setOnFrameAvailableListener(this)
        myFilter = MyFilter(cameraView.context)
    }

    //步骤三
    override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
        Log.i(TAG,"onSurfaceChanged")
        myFilter.setSize(width,height)
    }

    //步骤四 (步骤四步骤五循环)
    override fun onDrawFrame(gl: GL10?) {
        Log.i(TAG,"onDrawFrame:"+textures[0])
        //[刷新]更新摄像头最新的数据到GPU内存中
        cameraTexture.updateTexImage()
        cameraTexture.getTransformMatrix(matrix)
        myFilter.setTransformMatrix(matrix)
        myFilter.onDraw(textures[0]) //摄像头采集的数据都在textures[0]纹理这里
    }

    //步骤一
    override fun onUpdated(output: Preview.PreviewOutput) {
        Log.i(TAG,"onUpdated")
        cameraTexture = output.surfaceTexture
    }

    //步骤五 (步骤四步骤五循环)
    override fun onFrameAvailable(surfaceTexture: SurfaceTexture?) {
        Log.i(TAG,"onFrameAvailable")
        //手动请求渲染
        cameraView.requestRender()
    }
}